package com.Dyj.Funtalk.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.ResponseBody;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.modelbiz.ChooseCardFromWXCardPackage;

import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Callback.*;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import xu.li.cordova.wechat.Constant;
import xu.li.cordova.wechat.bean.WeiXinToken;
import xu.li.cordova.wechat.bean.WeiXinUserInfo;

import xu.li.cordova.wechat.Wechat;

/**
 * Created by xu.li<AthenaLightenedMyPath@gmail.com> on 9/1/15.
 */
public class EntryActivity extends Activity implements IWXAPIEventHandler {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IWXAPI api = Wechat.getWxAPI(this);

        if (api == null) {
            startMainActivity();
        } else {
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);

        IWXAPI api = Wechat.getWxAPI(this);
        if (api == null) {
            startMainActivity();
        } else {
            api.handleIntent(intent, this);
        }

    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d(Wechat.TAG, resp.toString());

        CallbackContext ctx = Wechat.getCurrentCallbackContext();

        if (ctx == null) {
            startMainActivity();
            return ;
        }

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        auth(resp);
                        break;
                    case ConstantsAPI.COMMAND_CHOOSE_CARD_FROM_EX_CARD_PACKAGE:
                        plunckInvoiceData(resp);
                        break;
                    case ConstantsAPI.COMMAND_PAY_BY_WX:
                    default:
                        ctx.success();
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_USER_CANCEL);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_AUTH_DENIED);
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_SENT_FAILED);
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_UNSUPPORT);
                break;
            case BaseResp.ErrCode.ERR_COMM:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_COMMON);
                break;
            default:
                ctx.error(Wechat.ERROR_WECHAT_RESPONSE_UNKNOWN);
                break;
        }

        finish();
    }

    @Override
    public void onReq(BaseReq req) {
        finish();
    }

    protected void startMainActivity() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(getApplicationContext().getPackageName());
        getApplicationContext().startActivity(intent);
    }

    protected void auth(BaseResp resp) {
        SendAuth.Resp res = ((SendAuth.Resp) resp);
        Log.d(Wechat.TAG, res.toString());
        // get current callback context
        CallbackContext ctx = Wechat.getCurrentCallbackContext();
        if (ctx == null) {
            return ;
        }
        JSONObject response = new JSONObject();
        try {
            response.put("code", res.code);
            response.put("state", res.state);
            response.put("country", res.country);
            response.put("lang", res.lang);
            getAccessToken(res);
        } catch (JSONException e) {
            Log.e(Wechat.TAG, e.getMessage());
        }
//        ctx.success(response);
    }


    /**
     * 获取AccessToken
     * @param res
     */
    private void getAccessToken(SendAuth.Resp  res) {
        CallbackContext ctx = Wechat.getCurrentCallbackContext();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid="+ Constant.WECHAT_APPID+"&secret="+ Constant.WECHAT_SECRET+
                "&code="+res.code+"&grant_type=authorization_code";
        Log.i("zzsun", "123123");
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {
                Gson gson = new Gson();
                WeiXinToken wxToken = gson.fromJson(response.body().charStream(), WeiXinToken.class);
                Log.i("zzsun", wxToken.getAccess_token());
                getRefreshToken(wxToken);
            }
            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }
        });



    }

    /**
     * 刷新accessToken
     * @param tokenBean
     */
    private void getRefreshToken(WeiXinToken tokenBean) {
        CallbackContext ctx = Wechat.getCurrentCallbackContext();
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+Constant.WECHAT_APPID+"&grant_type=refresh_token&refresh_token="+tokenBean.getRefresh_token();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {
                Gson gson = new Gson();
                WeiXinToken wxToken = gson.fromJson(response.body().charStream(), WeiXinToken.class);
                Log.i("zzsun2", wxToken.getAccess_token());
                getWeiUserInfo(wxToken);
            }
            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }
        });



    }

    /**
     * 获取用户信息
     * @param weiXinToken
     */
    private void getWeiUserInfo(WeiXinToken weiXinToken) {
        CallbackContext ctx = Wechat.getCurrentCallbackContext();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+
                weiXinToken.getAccess_token()+"&openid="+weiXinToken.getOpenid();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {
                Gson gson = new Gson();
                WeiXinUserInfo wxInfo = gson.fromJson(response.body().charStream(), WeiXinUserInfo.class);
                JSONObject _response = new JSONObject();
                try {
                    _response.put("unionid", wxInfo.getUnionid());
                    _response.put("nickname", wxInfo.getNickname());
                    _response.put("sex", wxInfo.getSex());
                    _response.put("province", wxInfo.getProvince());
                    _response.put("city", wxInfo.getCity());
                    _response.put("country", wxInfo.getCountry());
                    _response.put("headimgurl", wxInfo.getHeadimgurl());
                    Log.i("zzsun3",  wxInfo.getNickname());
                    CallbackContext ctx = Wechat.getCurrentCallbackContext();
                    ctx.success(_response);
                } catch (JSONException e) {
                    Log.e(Wechat.TAG, e.getMessage());
                }

            }
            @Override
            public void onFailure(Request arg0, IOException arg1) {

            }
        });

    }

    protected void plunckInvoiceData(BaseResp resp) {

            CallbackContext ctx = Wechat.getCurrentCallbackContext();
            ChooseCardFromWXCardPackage.Resp resp1 = (ChooseCardFromWXCardPackage.Resp) resp;
            JSONObject response = new JSONObject();

            try {
                JSONArray resp2 = new JSONArray(resp1.cardItemList);
                response.put("data", resp2);
            } catch (JSONException e) {
                Log.e(Wechat.TAG, e.getMessage());
            }

            ctx.success(response);
        }
}
